package com.tdx.blog_nowcoder.config;

import com.tdx.blog_nowcoder.utils.DumpJSONToString;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

import static com.tdx.blog_nowcoder.constant.UserRoleConstant.ROLE_USER;
import static com.tdx.blog_nowcoder.constant.UserRoleConstant.ROLE_ADMIN;
import static com.tdx.blog_nowcoder.constant.UserRoleConstant.ROLE_UP;

/**
* @description: TODO
* @author 何可人
* @date 2022/7/8 11:14
* @version 1.0
*/
@Configuration
public class SecurityConfig  {

    @Bean
    WebSecurityCustomizer webSecurityCustomizer() {
        return new WebSecurityCustomizer() {
            @Override
            public void customize(WebSecurity web) {
                web.ignoring().antMatchers("/resources/**");
            }
        };
    }


     @Bean
     public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
         // 授权
         http.authorizeRequests()
                 .antMatchers(
                         "/user/setting",
                         "/user/imgUpload",
                         "/user/profile/**",
                         "/discuss/add",
                         "/comment/add/**",
                         "/message/**",
                         "/like",
                         "/follow",
                         "/unfollow",
                         "/followers/**",
                         "/followees/**"
                 )
                 .hasAnyAuthority(
                         ROLE_USER,
                         ROLE_ADMIN,
                         ROLE_UP
                 )
                 .antMatchers(
                         "/discuss/top",
                         "/discuss/wonderful"
                 )
                 .hasAnyAuthority(ROLE_UP)
                 .antMatchers(
                         "/discuss/delete"

                 )
                 .hasAnyAuthority(
                         ROLE_ADMIN
                 )
                 .anyRequest().permitAll()
                 .and().csrf().disable();

         http.exceptionHandling().authenticationEntryPoint(new AuthenticationEntryPoint() {
             @Override //未登录
             public void commence(HttpServletRequest request, HttpServletResponse response,
                                  AuthenticationException authException) throws IOException, ServletException {

                 String xRequestedWith = request.getHeader("x-requested-with");
                 if ("XMLHttpRequest".equals(xRequestedWith)) {
                     response.setContentType("application/plain;charset=utf-8");
                     PrintWriter writer = response.getWriter();
                     writer.write(DumpJSONToString.getJsonString(403, "你还没有登录哦!"));
                 } else {
                     System.out.println("authenticationEntryPoint~~~~~~~~~~~~~~~~~~~~~~~~~");
                     response.sendRedirect(request.getContextPath() + "/login");
                 }
             }
         }).accessDeniedHandler(new AccessDeniedHandler() {
             @Override // 没有权限操作
             public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
                 String xRequestedWith = request.getHeader("x-requested-with");
                 if ("XMLHttpRequest".equals(xRequestedWith)) {
                     response.setContentType("application/plain;charset=utf-8");
                     PrintWriter writer = response.getWriter();
                     writer.write(DumpJSONToString.getJsonString(403, "你没有访问此功能的权限!"));
                 } else {
                     System.out.println("AccessDeniedHandler~~~~~~~~~~~~~~~~~~~~~~~~~");
                     response.sendRedirect(request.getContextPath() + "/denied");
                 }
             }
         });

         // Security底层默认会拦截/logout请求,进行退出处理.
         // 覆盖它默认的逻辑,才能执行我们自己的退出代码.

         http.logout().logoutUrl("/securitylogout");


         return http.build();

     }




}
